package fairygui.editor.handlers
{
   import fairygui.GObject;
   import fairygui.editor.Consts;
   import fairygui.editor.OpenProjectWindow;
   import fairygui.editor.animation.AniDef;
   import fairygui.editor.utils.BulkTasks;
   import fairygui.editor.utils.Utils;
   import fairygui.editor.utils.UtilsFile;
   import fairygui.editor.utils.UtilsStr;
   import fairygui.utils.GTimers;
   import flash.filesystem.File;
   import flash.system.System;
   
   public class UpgradeHandler
   {
       
      
      private var _win:OpenProjectWindow;
      
      private var _msg:GObject;
      
      private var _sourceFolder:File;
      
      private var _targetFolder:File;
      
      private var _assetsFolder:File;
      
      private var _objsFolder:File;
      
      private var _settingsFolder:File;
      
      private var _devCode:String;
      
      private var _nextId:uint;
      
      private var _useAtlas:Boolean;
      
      private var _publishPath:Object;
      
      private var _zipExt:String;
      
      private var _tasks:BulkTasks;
      
      public function UpgradeHandler()
      {
         super();
      }
      
      public function open(param1:OpenProjectWindow, param2:File) : void
      {
         var win:OpenProjectWindow = param1;
         var sourceFolder:File = param2;
         this._win = win;
         UtilsFile.browseForDirectory(Consts.g.text313,function(param1:File):void
         {
            run(sourceFolder,param1);
         });
      }
      
      private function run(param1:File, param2:File) : void
      {
         var xml:XML = null;
         var sourceFolder:File = param1;
         var targetFolder:File = param2;
         this._win.view.getChild("upgrade").visible = true;
         this._msg = this._win.view.getChild("upgradeMsg");
         this._devCode = Utils.genDevCode();
         this._nextId = 0;
         this._publishPath = {};
         this._sourceFolder = sourceFolder;
         this._targetFolder = targetFolder;
         var oldProjectXML:XML = new XML(UtilsFile.loadString(sourceFolder.resolvePath("project.xml")));
         var str:String = oldProjectXML.@type;
         this._useAtlas = str != "Flash";
         var projectXML:XML = <projectDescription/>;
         projectXML.@id = oldProjectXML.@id;
         projectXML.@type = oldProjectXML.@type;
         projectXML.@version = "3";
         this._assetsFolder = targetFolder.resolvePath("assets");
         this._assetsFolder.createDirectory();
         this._settingsFolder = targetFolder.resolvePath("settings");
         this._settingsFolder.createDirectory();
         this._objsFolder = targetFolder.resolvePath(".objs");
         this._objsFolder.createDirectory();
         UtilsFile.saveXML(targetFolder.resolvePath(oldProjectXML.@name + ".fairy"),projectXML);
         this.convertSettings(oldProjectXML);
         this._tasks = new BulkTasks(1);
         var packages:XMLList = oldProjectXML.packages["package"];
         for each(xml in packages)
         {
            this._tasks.addTask(this.convertPkg,xml);
         }
         this._tasks.start(function():void
         {
            var _loc1_:File = null;
            var _loc2_:Object = null;
            if(_zipExt)
            {
               _loc1_ = _settingsFolder.resolvePath("Publish.json");
               if(_loc1_.exists)
               {
                  _loc2_ = UtilsFile.loadJSON(_loc1_);
                  _loc2_.fileExtension = _zipExt;
                  UtilsFile.saveJSON(_loc1_,_loc2_);
               }
            }
            _win.openProject(targetFolder.nativePath);
         });
      }
      
      private function convertSettings(param1:XML) : void
      {
         var workspace:Object = null;
         var data:Object = null;
         var cs:Object = null;
         var cxml:XML = null;
         var tmpMap:Object = null;
         var str:String = null;
         var publish_path:Object = null;
         var path:String = null;
         var maxUse:int = 0;
         var defaultPublishPath:String = null;
         var pkgId:String = null;
         var t:int = 0;
         var ss:Object = null;
         var col:XMLList = null;
         var dxml:XML = null;
         var key:String = null;
         var value:String = null;
         var xml:XML = param1;
         try
         {
            workspace = UtilsFile.loadJSON(this._sourceFolder.resolvePath("projectSettings.json"));
            if(workspace != null)
            {
               tmpMap = {};
               publish_path = workspace.publish_path;
               if(publish_path)
               {
                  for each(path in publish_path)
                  {
                     t = tmpMap[path];
                     t = t + 1;
                     tmpMap[path] = t;
                  }
                  maxUse = 0;
                  for(path in tmpMap)
                  {
                     t = tmpMap[path];
                     if(t > maxUse)
                     {
                        maxUse = t;
                        defaultPublishPath = path;
                     }
                  }
                  for(pkgId in publish_path)
                  {
                     path = publish_path[pkgId];
                     if(path != defaultPublishPath)
                     {
                        this._publishPath[pkgId] = path.replace(/\\\\/g,"\\");
                     }
                  }
                  delete workspace.publish_path;
               }
               UtilsFile.saveJSON(this._objsFolder.resolvePath("workspace.json"),workspace);
            }
            data = {};
            if(defaultPublishPath)
            {
               data.path = defaultPublishPath.replace(/\\\\/g,"\\");
            }
            cs = {};
            data.codeGeneration = cs;
            cs.codePath = String(xml.@targetPath);
            cs.classNamePrefix = String(xml.@classNamePrefix);
            cs.memberNamePrefix = String(xml.@memberNamePrefix);
            cs.packageName = String(xml.@packageName);
            str = xml.@ignoreNoname;
            if(str)
            {
               cs.ignoreNoname = str == "true";
            }
            str = xml.@getMemberByName;
            if(str)
            {
               cs.getMemberByName = str == "true";
            }
            str = xml.@codeType;
            if(str)
            {
               cs.codeType = str;
            }
            UtilsFile.saveJSON(this._settingsFolder.resolvePath("Publish.json"),data,true);
            data = {};
            cxml = xml.textSetting[0];
            if(cxml)
            {
               str = cxml.@font;
               if(str)
               {
                  data.font = str;
               }
               str = cxml.@size;
               if(str)
               {
                  data.fontSize = parseInt(str);
               }
               str = cxml.@color;
               if(str)
               {
                  data.textColor = str;
               }
               str = cxml.@originalPosition;
               if(str == "false")
               {
                  data.fontAdjustment = false;
               }
            }
            cxml = xml.colorScheme[0];
            if(cxml)
            {
               str = cxml.@value;
               data.colorScheme = str.split("\r\n");
            }
            cxml = xml.fontSizeScheme[0];
            if(cxml)
            {
               str = cxml.@value;
               data.fontSizeScheme = str.split("\r\n");
            }
            cxml = xml.scrollBars[0];
            if(cxml)
            {
               ss = {};
               data.scrollBars = ss;
               ss.vertical = String(cxml.@vertical);
               ss.horizontal = String(cxml.@horizontal);
               ss.defaultDisplay = String(cxml.@defaultDisplay);
            }
            UtilsFile.saveJSON(this._settingsFolder.resolvePath("Common.json"),data,true);
            cxml = xml.customProps[0];
            if(cxml)
            {
               data = {};
               col = cxml.elements();
               for each(dxml in col)
               {
                  key = String(dxml.@key);
                  value = String(dxml.@value);
                  data[key] = value;
               }
               UtilsFile.saveJSON(this._settingsFolder.resolvePath("CustomProperties.json"),data,true);
            }
            return;
         }
         catch(err:Error)
         {
            return;
         }
      }
      
      private function convertPkg() : void
      {
         var itemXML:XML = null;
         var itemXML2:XML = null;
         var tmpXML:XML = null;
         var cname:String = null;
         var path:String = null;
         var name:String = null;
         var str:String = null;
         var folderId:String = null;
         var pkgXML2:XML = null;
         var publishXML:XML = null;
         var file1:File = null;
         var file2:File = null;
         var ani:AniDef = null;
         var pkgId:String = this._tasks.taskData.@id;
         var pkgName:String = this._tasks.taskData.@name;
         this._msg.text = UtilsStr.formatString(Consts.g.text315,pkgName);
         var pkgFolder1:File = this._sourceFolder.resolvePath(pkgName);
         if(!pkgFolder1.exists)
         {
            this._tasks.finishItem();
            return;
         }
         var pkgXML1:XML = UtilsFile.loadXML(pkgFolder1.resolvePath("package.xml"));
         if(pkgXML1 == null)
         {
            this._tasks.finishItem();
            return;
         }
         var pkgFolder2:File = this._assetsFolder.resolvePath(pkgName);
         pkgFolder2.createDirectory();
         var folders:Object = {};
         var resources:XMLList = pkgXML1.resources.elements();
         for each(itemXML in resources)
         {
            name = itemXML.@name;
            itemXML.@name = name.replace(/[\:\/\\\*\?<>\|]/g,"_");
         }
         for each(itemXML in resources)
         {
            cname = itemXML.name().localName;
            if(cname == "folder")
            {
               path = this.getPath(resources,itemXML);
               folders[itemXML.@id] = path;
               pkgFolder2.resolvePath("." + path).createDirectory();
            }
         }
         pkgXML2 = <packageDescription><resources/></packageDescription>;
         pkgXML2.@id = pkgId;
         str = pkgXML1.@jpegQuality;
         if(str)
         {
            pkgXML2.@jpegQuality = str;
         }
         str = pkgXML1.@compressPNG;
         if(str)
         {
            pkgXML2.@compressPNG = str;
         }
         for each(itemXML in resources)
         {
            cname = itemXML.name().localName;
            if(cname != "folder")
            {
               if(cname == "jta")
               {
                  cname = "movieclip";
               }
               itemXML2 = new XML("<" + cname + "/>");
               pkgXML2.resources.appendChild(itemXML2);
               itemXML2.@id = itemXML.@id;
               str = UtilsStr.getFileExt(itemXML.@file);
               name = itemXML.@name;
               if(UtilsStr.getFileExt(name) == str)
               {
                  if(itemXML.@exported != "true")
                  {
                     name = name.replace(/\./g,"_");
                  }
               }
               itemXML2.@name = name + (!!str?"." + str:"");
               folderId = itemXML.@folder;
               if(folderId)
               {
                  path = folders[folderId];
                  if(!path)
                  {
                     path = "/";
                  }
               }
               else
               {
                  path = "/";
               }
               itemXML2.@path = path;
               str = itemXML.@exported;
               if(str)
               {
                  itemXML2.@exported = str;
               }
               if(cname == "image" || cname == "movieclip")
               {
                  str = itemXML.@includedInAtlas;
                  if(str)
                  {
                     if(str == "no")
                     {
                        itemXML2.@atlas = "alone";
                     }
                     else if(str != "yes" && str != "default" && str != "0")
                     {
                        itemXML2.@atlas = str;
                     }
                  }
                  str = itemXML.@qualityOption;
                  if(str)
                  {
                     if(str != "package" && !(str == "source" && this._useAtlas) && (str == "source" || str == "custom"))
                     {
                        itemXML2.@qualityOption = itemXML.@qualityOption;
                     }
                  }
                  str = itemXML.@scale;
                  if(str)
                  {
                     itemXML2.@scale = str;
                  }
                  str = itemXML.@scale9grid;
                  if(str)
                  {
                     itemXML2.@scale9grid = str;
                  }
                  str = itemXML.@gridTile;
                  if(str)
                  {
                     itemXML2.@gridTile = str;
                  }
                  str = itemXML.@quality;
                  if(str)
                  {
                     itemXML2.@quality = str;
                  }
               }
               file1 = pkgFolder1.resolvePath(itemXML.@file);
               file2 = pkgFolder2.resolvePath("." + path + itemXML2.@name);
               if(cname == "movieclip")
               {
                  ani = new AniDef();
                  try
                  {
                     ani.load(UtilsFile.loadBytes(file1));
                     UtilsFile.saveBytes(file2,ani.save());
                  }
                  catch(err:Error)
                  {
                  }
               }
               else if(cname == "font")
               {
                  UtilsFile.copyFile(file1,file2);
                  file1 = pkgFolder1.resolvePath(itemXML.@id + "_.png");
                  if(file1.exists)
                  {
                     file2 = pkgFolder2.resolvePath("." + path + name + "_atlas.png");
                     UtilsFile.copyFile(file1,file2);
                     tmpXML = <image/>;
                     tmpXML.@id = this.getNextId();
                     tmpXML.@name = name + "_atlas.png";
                     tmpXML.@path = itemXML2.@path;
                     str = itemXML.@atlas;
                     if(str)
                     {
                        if(str == "no")
                        {
                           tmpXML.@atlas = "alone";
                        }
                        else if(str != "yes" && str != "default" && str != "0")
                        {
                           tmpXML.@atlas = str;
                        }
                     }
                     pkgXML2.resources.appendChild(tmpXML);
                     itemXML2.@texture = tmpXML.@id;
                  }
               }
               else
               {
                  UtilsFile.copyFile(file1,file2);
               }
            }
         }
         publishXML = pkgXML1.publish[0];
         if(publishXML)
         {
            if(this._publishPath[pkgId])
            {
               publishXML.@path = this._publishPath[pkgId];
            }
            str = publishXML.@singlePackage;
            if(str == "true")
            {
               publishXML.@packageCount = "1";
            }
            str = publishXML.@zipExt;
            if(str)
            {
               this._zipExt = str;
            }
            delete publishXML.@zipExt;
            pkgXML2.appendChild(publishXML);
         }
         UtilsFile.saveXML(pkgFolder2.resolvePath("package.xml"),pkgXML2);
         System.disposeXML(pkgXML1);
         System.disposeXML(pkgXML2);
         GTimers.inst.add(12,1,this._tasks.finishItem);
      }
      
      public function getNextId() : String
      {
         return this._devCode + (this._nextId++).toString(36);
      }
      
      private function getPath(param1:XMLList, param2:XML) : String
      {
         var p:XML = null;
         var resources:XMLList = param1;
         var cur:XML = param2;
         var ret:Array = [];
         ret.push(cur.@name);
         var parentFolderId:String = cur.@folder;
         while(parentFolderId != "")
         {
            p = resources.(@id == parentFolderId)[0];
            if(!p)
            {
               break;
            }
            ret.push(p.@name);
            parentFolderId = p.@folder;
            if(ret.indexOf(parentFolderId) != -1)
            {
               break;
            }
         }
         ret.reverse();
         if(ret.length == 0)
         {
            return "/";
         }
         return "/" + ret.join("/") + "/";
      }
   }
}
